import React, { useEffect, useMemo, useState } from 'react';
import { useRequest } from 'ahooks';
import styles from './index.module.less';
import dayjs from 'dayjs';
import { HisValItem, HisVal, FundsObj } from '../../../type';
import { dayFormatter, getBuyDataLocalKey } from '../../../utils';

//历史净值信息
const useHisDate = (fundInfo: FundsObj) => {
  //购买日期
  const [buyObj, setBuyObj] = useState<{
    date: number;
    val: number;
  }>();

  const { maxValObj, curValObj, hisList } = useMemo(() => {
    const { totalNetWorthData, netWorthData } = fundInfo;

    //转成可计算数组
    const datas = netWorthData
      .map(([FSRQ, DWJZ], index) => {
        return {
          FSRQ,
          DWJZ,
          LJJZ: totalNetWorthData[index][1],
        };
      })
      .reverse();

    //求累计净值最大值
    const LJJZMax = Math.max(...datas?.map((item) => Number(item?.LJJZ ?? 0)));
    //找到累计净值最大值的日期对象
    const _maxValObj = datas.find((item) => Number(item.LJJZ) === LJJZMax);

    return {
      hisList: datas,
      curValObj: {
        date: dayjs(datas?.[0]?.FSRQ).valueOf(),
        val: Number(datas?.[0]?.DWJZ ?? 0),
        ...datas?.[0],
      },
      maxValObj: {
        date: dayjs(_maxValObj?.FSRQ).valueOf(),
        //用单位净值的原因就是累计净值无法很好的算出回测
        val: Number(_maxValObj?.DWJZ ?? 0),
        ..._maxValObj,
      },
    };
  }, [fundInfo.code]);

  const setBuyDate = (time: number, save: boolean = true) => {
    const obj = hisList.find((item) => dayjs(item.FSRQ).valueOf() === time);

    //存本地
    if (save) {
      localStorage.setItem(getBuyDataLocalKey(fundInfo.code), String(time));
    }

    setBuyObj(() => ({
      code: fundInfo.code,
      date: time,
      dataText: dayjs(time).format('YYYY-MM-DD'),
      val: Number(obj?.DWJZ ?? 0),
    }));
  };

  useEffect(() => {
 
    const time = Number(localStorage.getItem(getBuyDataLocalKey(fundInfo.code)));
    setBuyDate(time, false);
  }, [fundInfo.code]);

  return { maxValObj, curValObj, buyObj, setBuyDate };
};
export default useHisDate;
